import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import fetch from 'API/fetch';

import Button from '@kuiper-components/button';
import Loading from '@kuiper-components/loading';

import s from './DialogContent.module.css';

export default function DialogContent({ className, uid, onClose }) {
	const [qrcode, setQrcodeState] = React.useState({ loading: true });

	React.useEffect(() => {
		if (!uid) return;
		fetch(`/api/v1/user/${uid}/wechat/qrcode`, { method: 'GET' })
			.then(x => {
				setQrcodeState({ ...x, loading: false, error: '' });
			})
			.catch(error => {
				console.error('QRCode 请求失败', error);
				setQrcodeState({ loading: false, error: error.message });
			});
	}, [uid]);

	const checkBindStatus = async () => {
		return fetch(`/api/v1/user/${uid}/wechat`)
			.then(x => {
				// eslint-disable-next-line camelcase
				if (!x?.wx_openid) {
					return setQrcodeState({ error: '微信未绑定成功，请重试' });
				}
				onClose();
			})
			.catch(() => {
				setQrcodeState({ error: '微信未绑定成功，请重试' });
			});
	};

	return (
		<div className={cn(className, s.dialogContent)}>
			<Loading show={qrcode.loading}>
				<div className={s.qrcode}>
					<img src={qrcode.url} />
				</div>
			</Loading>
			{qrcode.error && <div className={s.error}>{qrcode.error}</div>}
			<div className={s.actions}>
				<Button className={s.btn} onClick={onClose}>
					取消
				</Button>
				{/* <Button
					primary
					className={s.btn}
					disabled={!qrcode.url}
					onClick={checkBindStatus}
				>
					绑定完成
				</Button> */}
			</div>
		</div>
	);
}

DialogContent.propTypes = {
	className: PropTypes.string,
	uid: PropTypes.string,
	onClose: PropTypes.func,
};

DialogContent.defaultProps = {
	className: s.dialogContent,
};
